<template>
  <div class="management-container">
    <!-- 页面标题和操作区 -->
    <div class="page-header">
      <div class="header-title">
        <h1>菜单管理</h1>
        <p>管理系统菜单结构、排序和状态</p>
      </div>
      
      <div class="header-actions">
        <a-button type="primary" @click="handleAddMenu">
           <Icons.PlusOutlined /> 新增菜单
        </a-button>
         <a-button style="margin-left: 12px" @click="initData">
          <Icons.SyncOutlined :spin="refreshing" />
          初始化数据
        </a-button>
      </div>
    </div>
    
    <!-- 菜单树形表格 -->
    <a-card class="menu-table-card">
      <a-table
        :columns="columns"
        :data-source="menuList"
        :loading="tableLoading"
        row-key="key"
        :pagination="false"
        :expand-icon="expandIcon"
      >
        
        <template #bodyCell="{ column, record }">
            <!-- 状态列 -->
            <a-switch v-if="column.dataIndex === 'status'"
                v-model:checked="record.status"
                checked-children="启用"
                un-checked-children="禁用"
                @change="handleStatusChange(record, $event)"
            />
            <!-- 操作列 -->
            <div class="menu-actions" v-if="column.dataIndex === 'actions'">
                <a-button
                type="text"
                size="small"
                @click="handleAddSubMenu(record)"
                >
                <Icons.PlusOutlined />
                </a-button>
                <a-button
                type="text"
                size="small"
                @click="handleEditMenu(record)"
                >
                <Icons.EditOutlined />
                </a-button>
                <a-button
                type="text"
                size="small"
                danger
                @click="handleDeleteMenu(record)"
                :disabled="record.children && record.children.length > 0"
                >
                <Icons.DeleteOutlined />
                </a-button>
            </div>
            <!-- 图标列 -->
            <div v-if="column.dataIndex === 'icon'">
              <component :is="Icons[record.icon]" v-if="record.icon" />
              <span v-else>-</span>
            </div>
        </template>
        
        
      </a-table>
    </a-card>
    
    <!-- 新增/编辑菜单模态框 -->
    <a-modal
      :title="menuModal.title"
      :open="menuModal.visible"
      :confirm-loading="menuModal.loading"
      :maskClosable="false"
      @cancel="closeMenuModal"
      @ok="handleSaveMenu"
    >
      <a-form
        :model="menuForm"
        :rules="formRules"
        ref="menuFormRef"
        layout="vertical"
      >
        <a-form-item
          name="title"
          label="菜单名称"
          :has-feedback="true"
        >
          <a-input
            v-model:value="menuForm.title"
            placeholder="请输入菜单名称"
          />
        </a-form-item>
        
        <a-form-item
          name="key"
          label="菜单标识"
          :has-feedback="true"
        >
          <a-input
            v-model:value="menuForm.key"
            placeholder="请输入菜单标识"
          />
        </a-form-item>
        
        <a-form-item
          name="path"
          label="路由路径"
          :has-feedback="true"
        >
          <a-input
            v-model:value="menuForm.path"
            placeholder="请输入路由路径"
          />
        </a-form-item>
        
        <a-form-item
          name="icon"
          label="菜单图标"
        >
          <a-input
            v-model:value="menuForm.icon"
            placeholder="请输入图标类型，例如：ArrowUpOutlined"
          />
          <p class="form-hint">提示：使用Ant Design图标，留空则不显示图标</p>
        </a-form-item>
        
        <a-form-item
          name="parentTitle"
          label="父级菜单"
          :hidden="!menuForm.parentTitle"
        >
          <a-input
            v-model:value="menuForm.parentTitle"
            disabled
          />
        </a-form-item>
        
        <a-form-item
          name="sort"
          label="排序号"
          :has-feedback="true"
        >
          <a-input-number
            v-model:value="menuForm.sort"
            :min="0"
            placeholder="数字越小越靠前"
          />
        </a-form-item>
        
        <a-form-item
          name="status"
          label="状态"
        >
          <a-radio-group v-model:value="menuForm.status">
            <a-radio :value="true">启用</a-radio>
            <a-radio :value="false">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
        
        <a-form-item
          name="remark"
          label="备注"
        >
          <a-textarea
            v-model:value="menuForm.remark"
            placeholder="请输入备注信息"
            :rows="3"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, h, nextTick, onMounted } from 'vue';
import { message, Modal } from 'ant-design-vue';
import menuApi from '@/api/menu'
import * as Icons from '@ant-design/icons-vue';



// 状态管理
const menuList = ref([]);
const tableLoading = ref(false);
const refreshing = ref(false);

// 表格列定义
const columns = [
  {
    title: "菜单名称",
    dataIndex: "title",
    key: "title",
    ellipsis: true
  },
  {
    title: "标识",
    dataIndex: "key",
    key: "key",
    width: 150,
    ellipsis: true
  },
  {
    title: "图标",
    dataIndex: "icon",
    key: "icon",
    width: 80
  },
  {
    title: "路由路径",
    dataIndex: "path",
    key: "path",
    ellipsis: true
  },
  {
    title: "排序",
    dataIndex: "sort",
    key: "sort",
    width: 80
  },
  {
    title: "状态",
    dataIndex: "status",
    key: "status",
    width: 120
  },
  {
    title: "操作",
    dataIndex: "actions",
    key: "actions",
    width: 220,
    fixed: "right"
  }
];

// 菜单模态框状态
const menuModal = ref({
  visible: false,
  loading: false,
  title: "新增菜单",
  type: "add" // add, addSub, edit
});

// 菜单表单数据
const menuForm = ref({
  id: "",
  key: "",
  title: "",
  icon: "",
  path: "",
  sort: 0,
  status: true,
  remark: "",
  parentKey: "",
  parentTitle: ""
});

// 表单验证规则
const formRules = ref({
  title: [
    { required: true, message: "请输入菜单名称", trigger: "blur" }
  ],
  key: [
    { required: true, message: "请输入菜单标识", trigger: "blur" },
    { pattern: /^[a-z0-9-]+$/, message: "标识只能包含小写字母、数字和横杠", trigger: "blur" }
  ],
  path: [
    { required: true, message: "请输入路由路径", trigger: "blur" },
    { pattern: /^\/[a-z0-9-\/]*$/, message: "路径必须以/开头，只能包含小写字母、数字和横杠", trigger: "blur" }
  ],
  sort: [
    { required: true, message: "请输入排序号", trigger: "blur" },
    { type: "number", message: "排序号必须是数字", trigger: "blur" }
  ]
});

// 表单引用
const menuFormRef = ref(null);

// 打开新增菜单模态框
const handleAddMenu = () => {
  menuModal.value = {
    visible: true,
    loading: false,
    title: "新增菜单",
    type: "add"
  };
  
  resetMenuForm();
  menuForm.value.id = "";
  menuForm.value.parentKey = "";
  menuForm.value.parentTitle = "";

};

// 打开新增子菜单模态框
const handleAddSubMenu = (record) => {
  menuModal.value = {
    visible: true,
    loading: false,
    title: `新增"${record.title}"的子菜单`,
    type: "addSub"
  };
  
  resetMenuForm();
  menuForm.value.parentTitle = record.title;
  menuForm.value.parentKey = record._id;
};

// 打开编辑菜单模态框
const handleEditMenu = (record) => {
  menuModal.value = {
    visible: true,
    loading: false,
    title: "编辑菜单",
    type: "edit"
  };
  
  // 填充表单数据
  menuForm.value = {
    id: record._id,
    key: record.key,
    title: record.title,
    icon: record.icon,
    path: record.path,
    sort: record.sort,
    status: record.status,
    remark: record.remark || "",
    parentKey: record.parentKey || "",
    parentTitle: record.parentTitle || ""

  };
};

// 关闭菜单模态框
const closeMenuModal = () => {
  menuModal.value.visible = false;
  menuModal.value.loading = false;
};

// 重置菜单表单
const resetMenuForm = () => {
  if (menuFormRef.value) {
    menuFormRef.value.resetFields();
  }
  
  menuForm.value = {
    id: "",
    key: "",
    title: "",
    icon: "",
    path: "",
    sort: 0,
    status: true,
    remark: "",
    parentKey: "",
    parentTitle: ""
  };
};

// 保存菜单（新增或编辑）
const handleSaveMenu = async () => {
  if (!menuFormRef.value) return;
  
  try {
    // 表单验证
    await menuFormRef.value.validate();
    menuModal.value.loading = true;
    
    if (menuModal.value.type === "add" || menuModal.value.type === "addSub") {
      // 新增菜单
      const newMenu = {
        ...menuForm.value,
        children: []
      };
      if (menuModal.value.type === "addSub") {
        // 添加子菜单
        await menuApi.createMenu({...newMenu,parentId:menuForm.value.parentKey})
        await addSubMenuToParent(newMenu);
        message.success("子菜单创建成功");
      } else {
        await menuApi.createMenu({...newMenu,parentId:null})
        // 添加顶级菜单
        menuList.value.push(newMenu);
        // 按排序号排序
        menuList.value.sort((a, b) => a.sort - b.sort);
        message.success("菜单创建成功");
      }
    } else {
      // 编辑菜单
      await menuApi.updateMenu(menuForm.value.id,{...menuForm.value,parentId:menuForm.value.parentKey?menuForm.value.parentKey:null})
      await updateMenuData(menuForm.value);
      message.success("菜单更新成功");
    }
    
    // 关闭模态框
    closeMenuModal();
  } catch (error) {
    console.error("表单验证失败:", error);
  }
};

// 添加子菜单到父菜单
const addSubMenuToParent = (newMenu) => {
  const findAndAdd = (menuItems) => {
    for (let item of menuItems) {
      if (item._id === newMenu.parentKey) {
        if (!item.children) {
          item.children = [];
        }
        item.children.push(newMenu);
        // 按排序号排序
        item.children.sort((a, b) => a.sort - b.sort);
        return true;
      }
      
      if (item.children && item.children.length > 0) {
        if (findAndAdd(item.children)) {
          return true;
        }
      }
    }
    return false;
  };
  
  findAndAdd(menuList.value);
};

// 更新菜单数据
const updateMenuData = (updatedMenu) => {
  const findAndUpdate = (menuItems) => {
    for (let i = 0; i < menuItems.length; i++) {
      if (menuItems[i].key === updatedMenu.key) {
        menuItems[i] = {
          ...menuItems[i],
          ...updatedMenu,
          children: menuItems[i].children // 保持子菜单不变
        };
        return true;
      }
      
      if (menuItems[i].children && menuItems[i].children.length > 0) {
        if (findAndUpdate(menuItems[i].children)) {
          return true;
        }
      }
    }
    return false;
  };
  
  findAndUpdate(menuList.value);
};

// 更改菜单状态
const handleStatusChange = async (record, checked) => {
  const newStatus = checked;
  tableLoading.value = true;
  try {
   
    const findAndUpdateStatus = (menuItems) => {
      for (let item of menuItems) {
        if (item.key === record.key) {
          item.status = newStatus;
          return true;
        }
        
        if (item.children && item.children.length > 0) {
          if (findAndUpdateStatus(item.children)) {
            return true;
          }
        }
      }
      return false;
    };
    await menuApi.updateMenu(record._id,record)
    findAndUpdateStatus(menuList.value);
    message.success(`菜单已${newStatus ? '启用' : '禁用'}`);
    tableLoading.value = false;
  } catch (error) {
    tableLoading.value = false;
  }
};

// 删除菜单
const handleDeleteMenu = (record) => {
  // 确认删除
  Modal.confirm({
    content: `确定要删除菜单"${record.title}"吗？`,
    okText: "确认",
    cancelText: "取消",
    onOk: async () => {
      tableLoading.value = true;
      try {
        const deleteMenuFromList = (menuItems) => {
          for (let i = 0; i < menuItems.length; i++) {
            if (menuItems[i].key === record.key) {
              menuItems.splice(i, 1);
              return true;
            }
            
            if (menuItems[i].children && menuItems[i].children.length > 0) {
              if (deleteMenuFromList(menuItems[i].children)) {
                return true;
              }
            }
          }
          return false;
        };
        await menuApi.deleteMenu(record._id);
        deleteMenuFromList(menuList.value);
        message.success("菜单已删除");
        tableLoading.value = false;
      } catch (error) {
        tableLoading.value = false;
      }
    }
  });
};

const expandIcon = (props) => {
  // 如果没有子菜单，不显示展开图标
  if (props.record.children && props.record.children.length === 0) {
    return null;
  }
  
  // 处理展开/折叠点击事件
  const handleClick = (e) => {
    // 阻止事件冒泡，避免触发行点击事件
    e.stopPropagation();
    // 调用表格的展开/折叠方法
    props.onExpand(props.record);
  };
  
  // 使用 h 函数创建带点击事件的图标组件
  return h(
    'span',
    { 
      class: 'ant-table-row-expand-icon',
      onClick: handleClick,
      style: { cursor: 'pointer' }
    },
    [props.expanded ? h(Icons.CaretDownOutlined) : h(Icons.CaretRightOutlined)]
  );
};
// 获取菜单列表
const fetchMenuList = async () => {
  tableLoading.value = true;
  try {
    const data = await menuApi.getMenus();
    console.log("菜单列表数据:", data);
    menuList.value = data;
  } catch (error) {
    console.error("获取菜单列表失败:", error);
  } finally {
    tableLoading.value = false;
  }
  
}
// 重置初始化数据
const initData = () => {
  Modal.confirm({
    title: "确认初始化菜单吗？",
    okText: "确认",
    cancelText: "取消",
    onOk: async () => {
      menuList.value =  [];
      tableLoading.value = true;
      refreshing.value = true;
      menuForm.value = {
        key: "",
        title: "",
        icon: "",
        path: "",
        sort: 0,
        status: true,
        remark: "",
        parentKey: "",
        parentTitle: ""

      };
      menuModal.value = {
        visible: false,
        loading: false,
        title: "新增菜单",
        type: "add"
      };
      if (menuFormRef.value) {
        menuFormRef.value.resetFields();
      }
      try {
        await menuApi.initMenus();
        await nextTick();
        await fetchMenuList();
        message.success("菜单初始化成功");
      } catch (error) {
        console.error("初始化菜单失败:", error);
        message.error("初始化菜单失败");
      }finally {
        tableLoading.value = false;
        refreshing.value = false;
      }
    }

  })
}
onMounted(() => {
  fetchMenuList();
})
</script>

<style lang="scss" scoped>
::v-deep(.ant-table-row-expand-icon)::before,
::v-deep(.ant-table-row-expand-icon)::after{
  display: none;
}
.management-container {
  padding: 24px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 64px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  
  .header-title {
    h1 {
      margin: 0 0 8px 0;
      font-size: 20px;
      font-weight: 600;
      color: #1f2329;
    }
    p {
      margin: 0;
      color: #6b7280;
      font-size: 14px;
    }
  }
  
  .header-actions {
    display: flex;
  }
}

.menu-table-card {
  background-color: #fff;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);
}

.menu-actions {
  display: flex;
  gap: 4px;
  
  .ant-btn-icon-only {
    width: 24px;
    height: 24px;
    font-size: 14px;
  }
}

.form-hint {
  margin: 4px 0 0 0;
  padding: 0;
  color: #6b7280;
  font-size: 12px;
  line-height: 1.5;
}

// 树形表格样式优化
:deep(.ant-table-expanded-row) > td {
  background-color: #fafafa !important;
}

:deep(.ant-table-row-expand-icon) {
  margin-right: 4px;
}

:deep(.ant-table-tbody > tr > td) {
  transition: background-color 0.2s;
  
  &:hover {
    background-color: #f5f7fa;
  }
}

:deep(.ant-switch) {
  margin: 0;
}
</style>
